package com.cn.bukeManage.utils.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;

import com.cn.bukeManage.utils.MD5Utils.MD5Utils;
import com.cn.bukeManage.utils.picture.PictureUtils;


public class UploadUtils {
	/**
	 * 上传到本地服务器
	 * @param path
	 * @param name
	 * @param pictureFile
	 */
	public static void uploadLocalTomcat(String path,String name,MultipartFile pictureFile) {
		File dir=new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		
		//存到本地
		try {
			FileOutputStream fileOutputStream=new FileOutputStream(new File(dir,name));
			fileOutputStream.write(pictureFile.getBytes());
			fileOutputStream.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
	}
	/**
	 * 上传到七牛云
	 * @param path
	 * @param name
	 * @return
	 */
	public static int uploadQiNiu(String path,String name){
		String FilePath=path+"\\"+name;
		String key=name;
		UploadDemo uploadDemo=new UploadDemo();
		int stateCode=0;
		try {
			stateCode= uploadDemo.upload(FilePath, key);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return stateCode;
	}
	/**
	 * base64上传到七牛云 返回在七牛云的地址
	 * @param base
	 * @return
	 */
	public static String getImgNameOfUploadBase64(String base){
		if(base!=null){
			int indexOf = base.indexOf(",");
			if(base.length()<50){
				return base;
			}else {
				String substring = base.substring(indexOf+1);		
				String imgFilePath="..\\uploadImg";
				File file=new File(imgFilePath);
				if(file.exists()){
				}else {
					file.mkdirs();
				}
				String name=MD5Utils.getUUID();
				PictureUtils.GenerateImage(substring, imgFilePath+"\\"+name);
				int uploadQiNiu = UploadUtils.uploadQiNiu(imgFilePath,name);
				if (uploadQiNiu==200) {
					File file2=new File(imgFilePath+"\\"+name);
					if (file2.exists()) {
						file2.delete();
					}
					return name;
				}else {
					return "该图片上传失败!";
				}			
			}			
		}else{
			return "没传图片";
		}



	}
	
	
}